﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YAPL.Language.Core.Exceptions;
using YAPL.Language.Core.Types;

namespace YAPL.Language.Core.Lib.GlobalFunctions {
	public class ParseInt : YAPLFunction {
		private const string ARG = "arg";
		public ParseInt() : base(FunctionNames.ParseInt, GCL.Get(ClassNames.GlobalScope)) { }
		
		[Param(0,ARG)]
		public override YAPLObject Call(Scope scope) {
			ParseScope(scope);
			var arg = scope[ARG];
			if (arg is YAPLString) {
				YAPLObject result = null;
				try {
					result = new YAPLInt(int.Parse((arg as YAPLString).StrValue));
					return result;
				}
				catch (Exception) {
					throw new YAPLBadArgumentException("Couldn't parse argument", result);
				}
			}
			if (arg is YAPLFloat) {
				return new YAPLInt((int)(arg as YAPLFloat).FloatValue);
			}
			if (arg is YAPLInt)
				return new YAPLInt((arg as YAPLInt).IntValue);
			throw new YAPLBadArgumentException("Couldn't parse argument", arg);
		}

		public override bool CanPrecompute {
			get {
				return true;
			}
		}
	}
}
